package com.luzh.myspring.aop.framework;

import com.luzh.myspring.aop.AdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk代理类
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private final AdvisedSupport advised;

    public JdkDynamicAopProxy(AdvisedSupport advised) {
        this.advised = advised;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), advised.getTargetSource().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ReflectiveMethodInvocation methodInvocation = new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args);
        //如果匹配调用增强后的方法
        if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTargetClass())) {
            //执行自定义逻辑
            return advised.getMethodInterceptor().invoke(methodInvocation);
        }
        //直接执行被代理对象的方法
        return methodInvocation.proceed();
    }

}

